package com.hk.Mgr.web.controller.order;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.*;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.order.OrderStatements;
import com.hk.commons.entity.pay.FM;
import com.hk.commons.entity.product.HistoryPayment;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.sys.DataHelper;
import com.hk.commons.vo.HCOrderMsg;
import com.hk.commons.vo.UserCardMsg;
import com.hk.service.kyc.ICoupon;
import com.hk.service.order.*;
import com.hk.service.order.impl.HuochaiOrderImpl;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ISysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping(value = "/hc")
public class HCOrderInfoCtrl extends BaseCtrl {
	@Autowired
	private ISysUser userService;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IPayment paymentService;
	
	@Autowired
	private IHistoryPayment historyPaymentService;
	
	@Autowired
	private ICoupon couponService;

	@Autowired
	private IProductInfo productService;

	@Autowired
	private IOrderRouteInfo orderRouteService;

	@Autowired
	private IOrderStatements orderStatementsService;

	private Logger logger = LoggerFactory.getLogger(HCOrderInfoCtrl.class);


	@RequestMapping(value = "/pushOrderInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> pushOrderInfo(@RequestBody HCOrderMsg req) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		resp.setResult(true);
		resp.setResultCode(StatusCode.SUCCESS.key());

		if (req == null || req.getOrderId()== null || req.getAmount() == null || req.getDividend() == null
				|| req.getDividendDate() == null || req.getIdentity() == null || req.getOrderCreatedOn() == null
				|| req.getOrderTradeDate() == null || req.getPayentNo() == null || req.getPhoneNum() == null
				|| req.getUserName() == null){
			resp.setResult(false);
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		Long orderId = req.getOrderId();

		String key = ConstantsOrder.ORDER_HC_PRIX + String.valueOf(orderId);

		if ( !(RedisCilent.existsKey(key))){
			logger.info("order is not in the redis and will not insert orderId ={}", orderId);
			return resp;
		}

		logger.info("hc orderId ={}, push msg = {}", req.getOrderId(), req.toString());

		//启用多线程更新火柴订单
		ExecutorService executor = Executors.newFixedThreadPool(1);

		Runnable task = new Runnable() {
			public void run() {
				logger.info("checkLog in thread task orderid ={}", orderId);
				Boolean result = addOrderIntoDB(req);
				logger.info("checkLog in thread task result  ={}", result);
				if(result ){
					RedisCilent.delKey(key);
					logger.info("the record has insert into db and will delete the key={}", key);
				}
			}
		};
		executor.execute(task);
		executor.shutdown();
		return resp;
	}


	private Boolean addOrderIntoDB(HCOrderMsg req) {

		logger.info("checkLog in thread task addOrderIntoDB  will start orderid ={}, req={}", req.getOrderId(), req.toString());

		Long orderId = req.getOrderId();

		String userName = req.getUserName();
		String identity = req.getIdentity();
		String paymentNo = req.getPayentNo();
		String phoneNum = req.getPhoneNum();

		BigDecimal dividend = req.getDividend();
		BigDecimal amount = req.getAmount();

		logger.info("checkLog order in the redis before orderId ={}", orderId);

		OrderInfo orderInfo = HuochaiOrderImpl.getOrderFromRedis(orderId);

		if(orderInfo == null){
			logger.info("checkLog order in the redis after orderId ={}, orderInfo is null", orderId);
			return false;
		}

		logger.info("checkLog order in the redis after orderId ={}, orderInfo={}", orderId, orderInfo.toString());
		Long userId = orderInfo.getUserId();
		Long paymentId = addNewPayment(userId, paymentNo, identity,
				userName, phoneNum);

		Long userCardId = orderInfo.getUserCardId();

		orderInfo.setDividendDate(req.getDividendDate());
		orderInfo.setPayStatus(ConstantOrderStatus.PAY_STATUS_TRUE);
		orderInfo.setConfirmStatus(ConstantOrderStatus.CONFIRM_STATUS__TRUE);
		orderInfo.setDividend(req.getDividend());
		orderInfo.setPaymentId(paymentId);
		orderInfo.setOrderTradeDate(req.getOrderTradeDate());
		orderInfo.setOrderConfirmDate(req.getOrderCreatedOn());
		orderInfo.setSuccessAmount(amount);
		orderInfo.setCompanyId(ConstantRoute.COMPANY_HUOCHAI);

		logger.info("checkLog in thread task before active card");

		couponService.activeCoupon(userCardId, userId, orderId, true);

		logger.info("checkLog in thread task after active card");

		ProductInfo productInfo = productService.findById(orderInfo.getProductId());
		int term = productInfo.getProTerm();

		//产品原有收益、产品原有收益率
		BigDecimal prodRate = DataHelper.chgPrecentToBigDecimal(productInfo.getMaxYearRate());
		orderInfo.setProRate(prodRate);
		orderInfo.setProdDividend(DataHelper.getDividend(prodRate, term, amount));

		//设置额外收益率为0
		BigDecimal extRate = BigDecimal.valueOf(0.00);
		BigDecimal extDividend = BigDecimal.valueOf(0.00);

		if (userCardId != null && couponService.getCouponInfo(userId, userCardId) != null) {
			UserCardMsg userCardMsg = couponService.getCouponInfo(userId, userCardId);
			//设置订单的优惠类型
			orderInfo.setBenefitType(userCardMsg.getCardType());

			orderInfo.setUserCardId(userCardId);
			extDividend = DataHelper.getDividend(userCardMsg.getFaceValue(), term, amount);
			orderInfo.setExtraDividend(extDividend);
			extRate = userCardMsg.getFaceValue();
			orderInfo.setExtRate(extRate);
			orderInfo.setUserCardRate(extRate);
			orderInfo.setUserCardDividend(extDividend);

			//如果使用的加息券，则更改产品的利息和原有收益
			BigDecimal rate = prodRate.subtract(extRate);
			orderInfo.setProRate(rate);
			orderInfo.setProdDividend(DataHelper.getDividend(rate, term, amount));
		}

		//设置产品的总收益率
		orderInfo.setTotalRate(prodRate);
		orderInfo.setRealPayAmt(amount);
		orderInfo.setPayBackAmt(amount.add(dividend));

		//设置真实付款金额
		orderInfo.setRealPayAmt(amount);

		//设置还款金额
		orderInfo.setPayBackAmt(amount.add(dividend));

		// 添加订单记录
		logger.info("******************** pushOrderInfo 即将把订单写入orderInfo 表中***********************");
		logger.info("orderInfo = " + orderInfo.toString());
		logger.info("checkLog in thread task before add order ");
		orderService.add(orderInfo);
		logger.info("checkLog in thread task after add order");
		orderRouteService.addByOrder(orderInfo);
		logger.info("checkLog in thread task after add order route");

		//更改产品的已募集额度
		productService.updAmountByPay(orderInfo.getProductId(), orderInfo.getSuccessAmount(), true);
		// 添加订单流水信息
		logger.info("will insert order into the orderStatements");
		OrderStatements orderStatements = new OrderStatements();
		ReqToModelHelper
				.copyReqValueToModel(orderInfo, orderStatements);
		orderStatementsService.add(orderStatements);

		return true;

	}


	/**
	 * 将支付信息保存在支付记录表中
	 *
	 * @param userId
	 *            用户id
	 * @param paymentNo
	 *            银行卡号
	 * @param identity
	 *            身份证号
	 * @param userName
	 *            用户姓名
	 * @param phoneNum
	 *            银行卡关联的手机号
	 */
	public Long addNewPayment(Long userId, String paymentNo, String identity,
							  String userName, String phoneNum) {
		Long paymentId = null;
		logger.info("updatePaymentInfo userId = " + userId + "  paymentNo = "
				+ paymentNo + "  identity = " + identity + " userName = "
				+ userName + "  phoneNum = " + phoneNum);

		// 更新用户的相关信息
		userService.upUserByPayment(userId, null, identity, userName);

		// 判断用户身份信息和卡片信息是否一致

		SysUser user = userService.findById(userId);

		if (identity != null && user.getIdentity() != null
				&& (!user.getIdentity().equalsIgnoreCase(identity))) {
			logger.info("身份证号码不一致  identityNo in DB  = " + user.getIdentity()
					+ " identityNo in payment = " + identity);
			return null;
		}

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("paymentNo", paymentNo);
		List<Payment> existPaymentList = paymentService.findByFilter(hqlFilter);
		String bankName=null;
		if (existPaymentList.size() > 0) {
			Payment existPayment = existPaymentList.get(0);
			if (StringHelper.isEmpty(existPayment.getAccountName())
					|| StringHelper.isEmpty(existPayment.getIdentityNo())
					|| StringHelper.isEmpty(existPayment.getPhone())) {
				existPayment.setAccountName(userName);
				existPayment.setPhone(phoneNum);
				existPayment.setIdentityNo(identity);
				paymentService.update(existPayment);
			}
			String huochaiCompany = paymentService.getCardCompany(
					ConstantRoute.COMPANY_HUOCHAI, existPayment);
			if ((ConstantRoute.COMPANY_HUOCHAI + "").equals(huochaiCompany)) {
				logger.info("该用户已在火柴绑该张卡，不能再次绑卡！userId={}", user.getId());
			} else {// 更新用户绑卡信息
				existPayment.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_SHOW);
				existPayment.setCts(System.currentTimeMillis());
				existPayment.setPhone(phoneNum);
				paymentService.setAddCardCompany(ConstantRoute.COMPANY_HUOCHAI,
						existPayment);
				paymentService.update(existPayment);
				try {
					user.setTieCard(CardStatusCode.PAYMENT_DISPLAY_SHOW);
					userService.update(user);
				} catch (Exception e) {
					logger.error("更新用户表异常！", e);
				}
			}
			paymentId = existPayment.getId();
			bankName=existPayment.getBankName();
		} else {
			Payment newPayment = new Payment();
			newPayment.setPaymentNo(paymentNo);
			newPayment.setIdentityNo(identity);
			newPayment.setAccountName(userName);
			newPayment.setPaymentNo(paymentNo);
			newPayment.setPhone(phoneNum);
			newPayment.setUserRegistPhone(user.getName());
			newPayment.setUserId(userId);
			newPayment.setCts(System.currentTimeMillis());
			newPayment.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_SHOW);
			newPayment.setSupportCompany(CardStatusCode.NEVER_BIND_CARD + ","
					+ ConstantRoute.COMPANY_HUOCHAI + ","
					+ CardStatusCode.NEVER_BIND_CARD);
			// 补全银行卡开户行等信息
			FM fm = GetBankInfoUtil.getBankCardInfo(newPayment.getPaymentNo());
			if (fm != null) {
				if (StringHelper.isNotEmpty(fm.getCnm())) {
					newPayment.setCardType(fm.getCtp());// 卡类型
					newPayment.setBankName(fm.getCnm());// 银行名称
					newPayment.setInsCard(fm.getInscd());// 银行机构号					
				}
			}
			paymentId = paymentService.add(newPayment);
			bankName=newPayment.getBankName();
			try {
				user.setTieCard(CardStatusCode.PAYMENT_DISPLAY_SHOW);
				userService.update(user);
			} catch (Exception e) {
				logger.error("更新用户表异常！", e);
			}
		}
		try {
			HistoryPayment historyPayment=new HistoryPayment();
			historyPayment.setCompany(ConstantRoute.COMPANY_HUOCHAI);
			historyPayment.setPaymentType(CardStatusCode.PAYMENT_TYPE_ADD);
			historyPayment.setNewBankNo(paymentNo);
			historyPayment.setUserId(userId);
			historyPayment.setPaymentId(paymentId);
			historyPayment.setNewBankName(bankName);
			historyPaymentService.add(historyPayment);
			
			//historyPaymentService.add(ConstantRoute.COMPANY_HUOCHAI, CardStatusCode.PAYMENT_TYPE_ADD, null, paymentNo, userId);
		} catch (Exception e) {
			logger.error("<--------------------------ERROR------------------------->");
			logger.error("HCOrderInfoCtrl火柴绑卡添加到绑卡历史表中异常!!",e);
		}
		return paymentId;
	}

}
